<template>
	<view class="hideCanvasView">
		<u-upload width="160" height="160" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10"></u-upload>
		<!-- 获取有水印的图片过程 必须使canvas显示 获取完成后在隐藏掉canvas 配合canvas样式定位 使其错位 -->
		<!-- canvas的隐藏 在小程序中 使用 v-if或display：none 都不生效   使用hidden属性 true隐藏 false显示 -->
		<!-- :hidden="flagC" -->
		<canvas  :style="{ width: canvasWidth, height: canvasHeight }" canvas-id="myCanvas" ></canvas>
	</view>
</template>

<script>
import QQMapWX from 'static/common/js/qqmap-wx-jssdk.js';
let qqmapsdk;
let lists = [];
export default {
	data() {
		return {
			fileList1: [],
			//水印变量
			flagC: false,
			canvasWidth: '',
			canvasHeight: '',
			photoIndex: 0,
			address: '' //图片位置
		};
	},
	onLoad() {
		//获取经纬度以及当前
		// #ifndef APP-PLUS
		// 实例化API核心类
		qqmapsdk = new QQMapWX({
			//key: '5WNBZ-2JYR6-SPUSL-M3WGH-U4KDT-K2FYV',
			key: 'E5NBZ-VV5CD-IL64J-HW7Q5-H2EQS-VZFVD'
		});
		// #endif
		let _this = this;
		uni.getFuzzyLocation({
			type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			success: res => {
				const latitude = res.latitude;
				const longitude = res.longitude;
				let location = longitude + ',' + latitude;
				console.log('location', JSON.stringify(res));
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: latitude,
						longitude: longitude
					},
					//location: e.detail.value.reverseGeo || '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
					//get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
					success: function (res) {
						//成功后的回调
						console.log('当前位置信息' + JSON.stringify(res));
						_this.address = res.result.address;
					},
					fail: function (error) {
						console.error(error);
					},
					complete: function (res) {
						console.log(res);
					}
				});
			}
		});
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this.fileList1.splice(event.index, 1);
		},
		// 新增图片
		afterRead(event) {
			this.photoIndex = 0;
			lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists = lists.map((item, index) => {
				let info = {
					name: event.name,
					...item,
					status: 'uploading',
					message: '上传中',
					cid: new Date().getTime() + index
				};
				this[`fileList${event.name}`].push(info);
				return info;
			});
			this.callAddWaterMart();
		},
		uploadImg(fileName, filePath, curIndex) {
			//fileName：h5图片没有带后缀，需手动拼上
			// #ifdef H5
			fileName = fileName + '.png';
			// #endif
			return getajax(this.$api.policy, {
				params: {
					fileName: fileName
				}
			})
				.then(da => {
					let data = da;
					let formData = {
						key: data.key,
						policy: data.policy,
						OSSAccessKeyId: data.accessid,
						signature: data.signature,
						success_action_status: '200'
					};
					console.log('获取key成功', formData);
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: data.host,
							filePath: filePath,
							name: 'file',
							formData: formData,
							success: function (res) {
								if (res.statusCode == 200) {
									res.data = data.key;
									resolve(res);
								} else {
									resolve();
								}
							},
							fail: function (err) {
								console.log('上传失败了');
								resolve();
							}
						});
					});
				})
				.catch(() => {});
		},

		// 调用添加水印的函数
		callAddWaterMart() {
			this.addWaterMark(() => {
				if (this.photoIndex < lists.length - 1) {
					this.photoIndex++;
					this.callAddWaterMart();
				} else {
					uni.hideLoading();
				}
			});
		},
		// 添加水印
		addWaterMark(callback) {
			this.flagC = false;
			let _this = this;
			uni.getImageInfo({
				// 注意此时的地址是正常的图片地址 以下是给图片添加水印返回新的url地址
				src: lists[_this.photoIndex].url,
				success: res => {
					let canvasWidth = null;
					let canvasHeight = null;
					uni.getSystemInfo({
						success: function (info) {
							console.log(info.pixelRatio);
							_this.canvasWidth = `${res.width / info.pixelRatio}px`;
							_this.canvasHeight = `${res.height / info.pixelRatio}px`;
							canvasWidth = res.width / info.pixelRatio;
							canvasHeight = res.height / info.pixelRatio;
						}
					});
					var ctx = uni.createCanvasContext('myCanvas');
					// 在自定义组件内 需要传递第二参数 this canvas才生效
					ctx.clearRect(0, 0, canvasWidth, canvasHeight);
					ctx.beginPath();
					console.log('lists[_this.photoIndex].url',lists[_this.photoIndex].url)
					ctx.drawImage(lists[_this.photoIndex].url, 0, 0, canvasWidth, canvasHeight); // 第一个参数是图片 第二、三是图片在画布位置 第四、五是将图片绘制成多大宽高（不写四五就是原图宽高）

					//这部分是水印的大小位置和数量
					let horizontal = canvasWidth / 4;
					let vertical = canvasHeight / 3;
					let fonstsize = canvasWidth / 30;
					ctx.setFontSize(fonstsize);
					ctx.setFillStyle('rgba(255,255,255,0.8)');
					let height1 = canvasHeight - 100;
					console.log('height1' + height1);
					console.log(_this.address);
					if (_this.address) {
						ctx.fillText(_this.address, 30, height1, fonstsize * 15 * 2);
					}
					let curTime = Number(new Date());
					let formatCurTime = uni.$u.timeFormat(curTime, 'yyyy年mm月dd日 hh时MM分ss秒');
					let height2 = canvasHeight - 50;
					console.log('height2' + height2);
					ctx.fillText(formatCurTime, 30, height2, fonstsize * 15 * 2);

					//ctx.restore();
					// 开始绘制添加水印的图片并显示在页面中
					ctx.draw(false, () => {
						setTimeout(() => {
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas',
								quality: 0.4,
								width: _this.canvasWidth,
								height: _this.canvasHeight,
								destWidth: _this.canvasWidth,
								destHeight: _this.canvasHeight,
								success: canvas2 => {
									console.log(123, canvas2.tempFilePath);
									console.log('图片信息', JSON.stringify(canvas2));
									lists[_this.photoIndex].url = canvas2.tempFilePath;
									lists[_this.photoIndex].thumb = canvas2.tempFilePath;
									_this.flagC = true;
									if (lists && lists.length > 0) {
										for (let i = 0; i < lists.length; i++) {
											let namelist = lists[i].url.split('/');
											let id = lists[i].cid;
											this.uploadImg(namelist[namelist.length - 1], lists[i].url).then(res => {
												let index = this[`fileList${lists[_this.photoIndex].name}`].findIndex(item => item.cid == id);
												// console.log('id', id, res);
												if (res && res.statusCode == 200) {
													let result = res.data;
													let item = this[`fileList${lists[_this.photoIndex].name}`][index];
													this[`fileList${lists[_this.photoIndex].name}`].splice(
														index,
														1,
														Object.assign(item, {
															status: 'success',
															message: '',
															url: '',
															fileUrl: result
														})
													);
													console.log(lists[_this.photoIndex].name);
													// fileListLen++;
												} else {
													uni.$u.toast('图片上传失败了');
													this[`fileList${lists[_this.photoIndex].name}`].splice(index, 1);
												}
											});
										}
									}
									callback();
								}
							});
							// 在自定义组件内 需要传递第二参数 this canvas才生效
							// }, this)
						}, 500);
					});
				}
			});
		}
	}
};
</script>

<style scoped>
	.hideCanvasView {
		position: relative;
	}
	
	.hideCanvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}
</style>
